package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderedMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@Api("定时任务接口")
public class OrderTask {
    @Autowired
    private OrderedMapper orderedMapper;

    @ApiOperation("超时未支付订单")
    @Scheduled(cron = "0 * * * * ?")
    public void orderTask() {
        log.info("计时任务开启" + LocalDateTime.now());
        //1.查询一下符合条件的订单
        LocalDateTime now = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = orderedMapper.getStatusAndOrderTime(Orders.PENDING_PAYMENT, now);
        //2.修改一下查询到的订单
        if (orders != null && !orders.isEmpty()) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.ORDERS_NUORDER_TIME);
                orderedMapper.update(order);
            }
        }
    }

    @ApiOperation("每天凌晨3点把已完成但是派送中的订单进行完成")
//    @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(cron = "0/5 * * * * ?")
    public void orderTaskAccomplish() {
        log.info("订单完单任务已开启"+LocalDateTime.now());
        //查询一下符合条件的订单
        LocalDateTime now = LocalDateTime.now().minusHours(3);
        List<Orders> ordersList = orderedMapper.getStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, now);
        //2.修改一下查询到的订单
        if (ordersList != null && !ordersList.isEmpty()) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderedMapper.update(orders);
            });
        }
    }

}
